﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using DevComponents.DotNetBar;
using System.Xml;
using FastReport;
using FastReport.Design;
using FastReport.Design.StandardDesigner;
using FastReport.DevComponents.DotNetBar;
using Kugar.Core.ExtMethod;
using Kugar.Core.WinForm.ExtMethod;

namespace Kugar.UI.WinForm.Print
{
    internal partial class FastReportDesinger : DevComponents.DotNetBar.Office2007Form
    {
        
        public FastReportDesinger()
        {
            InitializeComponent();

            //var desinger = new FastReport.Design.Designer();

            DesignerPlugins.Add(typeof(FastReportKugarExtToolBar));

            var c = new FastReport.Design.StandardDesigner.DesignerControl();
            c.AskSave = false;
            c.Dock = DockStyle.Fill;

            c.ShowMainMenu = true;
            c.ShowStatusBar = true;
            c.cmdSaveAs.CustomAction += cmdSaveAs_CustomAction;
            c.cmdOpen.CustomAction += cmdOpen_CustomAction;

            Designer = c;

            

            this.Controls.Add(c);
        }

        void cmdOpen_CustomAction(object sender, EventArgs e)
        {
            var openDialog = new OpenFileDialog();
            openDialog.AppendFilter("打印格式", "frp");
            openDialog.AddExtension = true;

            if (openDialog.ShowDialog(this)==DialogResult.OK)
            {
                var formatStr = "";

                using (var file=openDialog.OpenFile())
                {
                    using (var sr=new StreamReader(file))
                    {
                        formatStr = sr.ReadToEnd();
                        sr.Close();
                    }

                    file.Close();
                }

                if (string.IsNullOrWhiteSpace(formatStr))
                {
                    MessageBox.Show("文件格式错误");
                    return;
                }

                var rep = new FastReport.Report();

                try
                {
                    rep.LoadFromString(formatStr);
                }
                catch (Exception)
                {
                    MessageBox.Show("文件格式错误");
                    return;
                }

                if (!string.IsNullOrWhiteSpace(Designer.Report.Name))
                {
                    rep.SetName(Designer.Report.Name);
                }

                this.Designer.Report = rep;
                this.Designer.SetModified();
            }
           
        }

        void cmdSaveAs_CustomAction(object sender, EventArgs e)
        {
            var saveDialog = new SaveFileDialog();

            saveDialog.DefaultExt = "frp";
            saveDialog.AppendFilter("打印格式", "frp");
            if (saveDialog.ShowDialog(this) == DialogResult.OK)
            {
                var str=this.Designer.Report.SaveToStringBase64();

                using (var file=saveDialog.OpenFile())
                {
                    using (var wr=new StreamWriter(file))
                    {
                        wr.Write(str);
                        wr.Close();
                    }
                    file.Close();
                }

                
            }
        }

        public new DialogResult ShowDialog(IWin32Window target)
        {
            this.Text = @"打印设计器-" + (string.IsNullOrWhiteSpace(Designer.Report.Name) ? "未命名" : Designer.Report.Name);

            //Designer.cmdSaveAs.Enabled = false;

            Designer.cmdPreview.CustomAction += cmdPreview_CustomAction;

            //var builder=new FastReprtBuilder()

            Designer.Show();

            var t=base.ShowDialog(target);

            var newFormat = Designer.Report.SaveToString();
            //var oldFormat = "";
            //XmlDocument document=new XmlDocument();

            //if (document.SafeLoadXML(ReportFormat))
            //{
            //    oldFormat= document.GetElementsByTagName("FastReportFormat")[0].InnerText;
            //}
            //else
            //{
            //    oldFormat = ReportFormat;
            //}

            //if (string.Compare(newFormat, ReportFormat, true) == 0)
            {
                save();
            }

            

            return t;
        }

        void cmdPreview_CustomAction(object sender, EventArgs e)
        {
            var lastModify = Designer.Modified;

            Designer.ActiveReport.Show();

            Designer.Modified = lastModify;
        }

        public FastReport.Design.Designer Designer { private set; get; }

        public string ReportFormat { internal set; get; }

        private void FastReportDesinger_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (!this.Designer.Modified)
            {
                this.Designer.Modified = false;
                return;
            }

            var res = MessageBox.Show(@"当前打印格式已修改,是否保存?", @"保存", MessageBoxButtons.YesNoCancel);

            if (res == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
            else
            {
                if (res == DialogResult.No)
                {
                    this.Designer.Modified = false;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(Designer.Report.Name))
                    {
                        //var name=Kugar.Core.WinForm.InputBox.ShowInputBox("请输入名称", "输入打印格式的名称");

                        var frm = new frmModulePrintFormatSaving();

                        var name ="";

                        if (frm.ShowDialog(this) == DialogResult.OK)
                        {
                            name = frm.FormatName;
                        }
                        else
                        {
                            e.Cancel = true;
                            return;
                        }

                        if (string.IsNullOrWhiteSpace(name))
                        {
                            e.Cancel = true;
                            MessageBox.Show("未输入打印格式名称");
                            return;
                        }

                        Designer.Report.SetName(name);
                    }

                    save();

                    //if (string.IsNullOrWhiteSpace(Designer.Report.Name))
                    //{
                    //    var frm = new frmModulePrintFormatSaving();

                    //    if (frm.ShowDialog() == DialogResult.OK)
                    //    {
                    //        this.Designer.Report.FileName = frm.FormatName;
                    //        this.Designer.Report.SetName(frm.FormatName);
                    //        this.Designer.Name = frm.FormatName;
                    //        this.ReportFormat = Designer.Report.SaveToString();
                    //    }
                    //    else
                    //    {
                    //        e.Cancel = true;
                    //    }
                    //}
                }
            }

            this.DialogResult = res;
        }

        private void save()
        {
            //var formatXmlDocument = new XmlDocument();

            //var root = formatXmlDocument.CreateElement("Kugar");

            //var kugarPlugin = Designer.Plugins.Find("FastReportKugarExtToolBar") as FastReportKugarExtToolBar;

            //if (kugarPlugin != null)
            //{
            //    var fixRow = root.AppendChild("DetailBandFixRowPerPage");

            //    foreach (var fixRowConfig in kugarPlugin.FixRowConfigs)
            //    {
            //        fixRow.AppendChild(fixRowConfig.Key, fixRowConfig.Value.ToStringEx(0));
            //    }
            //}

            //var reportFormat = root.AppendChild("FastReportFormat");

            //reportFormat.InnerText = Designer.Report.SaveToString();

            this.ReportFormat = Designer.Report.SaveToString();

            //this.ReportFormat = formatXmlDocument.SaveToString();
        }
    }

    public class FastReportKugarExtToolBar : ToolbarBase
    {
        private ButtonItem fixRow = null;
        private Dictionary<string, int> _fixRowConfig = new Dictionary<string, int>();

        public FastReportKugarExtToolBar(Designer designer)
            : base(designer)
        {
            fixRow = new ButtonItem("FixPageRow", "固定行数");
            fixRow.Click += fixRow_Click;
            fixRow.Text = "固定行数";

            this.Name = "FastReportKugarExtToolBar";
            this.Text = "Kugar专用扩展工具栏";

            this.AutoHideVisible = true;
            this.CanAutoHide = true;
            this.CanHide = true;

            this.Items.Add(fixRow);

            //this.Show();

            this.DockLine = 0;
            //this.DockOffset = 490;
            //this.DockSide= eDockSide.Right;
            //this.Visible = true;

            

            var toolbar = this.Designer.Plugins.Find("StandardToolbar") as ToolbarBase;

            if (toolbar != null) toolbar.Parent.Controls.Add(this);
        }

        public override void UpdateContent()
        {
            base.UpdateContent();

            updateControls();
        }

        public override void SelectionChanged()
        {
            base.SelectionChanged();

            updateControls();
        }

        public Dictionary<string, int> FixRowConfigs { get { return _fixRowConfig; } }

        void fixRow_Click(object sender, EventArgs e)
        {
            var table = Designer.SelectedObjects[0] as DataBand;

            if (table==null)
            {
                return;   
            }

            var fixRowCountStr=Kugar.Core.WinForm.InputBox.ShowInputBox("明细固定行数配置", string.Format("表格{0}的每页固定行数", table.Name));

            if (!fixRowCountStr.IsNumeric())
            {
                MessageBox.Show("请输入数字");
                return;
            }

            var fixRowCount = fixRowCountStr.ToInt(0);

            if (fixRowCount<0)
            {
                fixRowCount = 0;
            }

            _fixRowConfig.AddOrUpdate(table.Name, fixRowCount);

        }


        private void updateControls()
        {
            if (this.Designer.SelectedObjects.Count <= 0 || !(this.Designer.SelectedObjects[0] is DataBand))
            {
                fixRow.Enabled = false;
            }
            else
            {
                fixRow.Enabled = true;
            }
        }

    }
}
